package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.io.IOException;
import java.nio.ByteBuffer;


public class OMDDATA extends AxdrType {
    private ByteBuffer dataCode = null;
    private OMD omd = null;
    private Data data = null;

    public OMDDATA() {
    }

    public void setDataCode(ByteBuffer dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(OMD omd, Data data) {
        this.omd = omd;
        this.data = data;
    }

    public void setOMD(OMD omd) {
        this.omd = omd;
    }

    public void setData(Data data) {
        this.data = data;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.omd = new OMD();
        codeLength += this.omd.decode(input);
        this.data = new Data();
        codeLength += this.data.decode(input);
        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength = 0;
        if (this.dataCode != null) {
            codeLength = this.dataCode.remaining();
            while (this.dataCode.hasRemaining()) {
                output.write(this.dataCode.get());
            }
        } else {
            if (this.data != null && this.omd != null) {
                codeLength += this.data.encode(output);
                codeLength += this.omd.encode(output);
            } else {
                throw new Exception("data || omd is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = ByteBuffer.wrap(revOStream.toByteArray());
    }

    @Override
    public String toString() {
        if (this.omd != null && this.data != null) {
            return "sequence: {" + "omd: " + this.omd + ", data: " + this.data + "}";
        } else {
            return "omd || data is null";
        }
    }
}



